package com.hntx.joymusic.view;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Scroller;


public class CenterRecyclerView extends RecyclerView{

    private static final String TAG = "CenterRecyclerView";
    private Scroller mScroller;
    private int mLastY = 0;
    private int mTargetPos;
    //用于设置自动平移时候的速度
    private float mPxPerMillsec = 0;

    public CenterRecyclerView(Context context) {
        super(context);
        init(context);
    }

    public CenterRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CenterRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mScroller = new Scroller(context);
    }


    @Override
    public void computeScroll() {
        super.computeScroll();
        //computeScrollOffset返回true表示滚动还在继续，持续时间应该就是startScroll设置的时间
        if (mScroller != null && mScroller.computeScrollOffset()) {
            scrollBy(0, mLastY - mScroller.getCurrY());
            mLastY = mScroller.getCurrY();
            postInvalidate();//让系统继续重绘，则会继续重复执行computeScroll
        }
    }

    /**
     * 将指定item平滑移动到整个view的中间位置
     *
     * @param position
     */
    public void smoothToCenter(int position) {
        int parentHeight = getHeight();//获取父视图的高度
        int childCount = getChildCount();//获取当前视图可见子view的总数
        //获取可视范围内的选项的头尾位置
        int firstvisiableposition = ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
        int count = getLayoutManager().getItemCount();//获取item总数
        mTargetPos = Math.max(0, Math.min(count - 1, position));//获取目标item的位置（参考listview中的smoothScrollToPosition方法）
        View targetChild = getChildAt(mTargetPos - firstvisiableposition);//获取目标item在当前可见视图item集合中的位置
        if (targetChild == null) return;
        int childTopPY = targetChild.getTop();//子view相对于父view的上边距
        int childBottomPY = targetChild.getBottom();//子view相对于父view的下边距


        int childHeight = targetChild.getHeight();
        int centerTop = parentHeight / 2 - childHeight / 2;//计算子view居中后相对于父view的左边距
        int centerBottom = parentHeight / 2 + childHeight / 2;//计算子view居中后相对于父view的右边距
        if (childTopPY > centerTop) {//子view左边距比居中view大（说明子view靠父view的右边，此时需要把子view向左平移
            //平移的起始位置就是子view的左边距，平移的距离就是两者之差
            mLastY = childTopPY;
            mScroller.startScroll(0, childTopPY, 0, centerTop - childTopPY, 600);//600为移动时长，可自行设定
            postInvalidate();
        } else if (childBottomPY < centerBottom) {
            mLastY = childBottomPY;
            mScroller.startScroll(0, childBottomPY, 0, centerBottom - childBottomPY, 600);
            postInvalidate();
        }
    }
}
